<template>
  <lay-card>
    <lay-row space="10">
      <lay-col md="24">
        <lay-textarea
          placeholder="只限于输入select语句进行查询和数据预览"
          v-model="sql_data"
        ></lay-textarea>
      </lay-col>
      <lay-col md="24">
        <lay-table
          :page="page"
          height="380px"
          :columns="columns"
          :loading="loading"
          :data-source="dataSource"
          v-model:selected-keys="selectedKeys"
          @change="change"
        >
        <template v-slot:toolbar>
          <lay-button size="sm" type="normal" @click="firstQuery">查询</lay-button>
        </template>
      </lay-table>
      </lay-col>
    </lay-row>
  </lay-card>
</template>

<script lang="ts">

export default {
    name: "TableDataView",
}
</script>

<script lang="ts" setup>
import {getCurrentInstance, reactive, ref} from "vue";
import {layer} from "@layui/layui-vue";
import {actSelectSql, selectCount} from "../../api/module/db";
import {openMsg} from "../../untils/tip";

const sql_data = ref("select * from dual;")

const loading = ref(false);

// title <==> table
const tableData = reactive({data: {id: '', db_id: '', database: '', title: '', type: 'db_table'}});

let instance2 = getCurrentInstance()

instance2?.proxy?.$Bus.on("on-table", (res: any) => {
  console.log("on-table result:");
  console.log(res);
  tableData.data = {id: res.id, db_id: res.dbLink, database: res.dbBase, title: res.name, type: 'db_table'}
  sql_data.value = "select * from " + tableData.data.database + "." + tableData.data.title + " where 1=1;"
})

const selectedKeys = ref([]);

const page = reactive({ current: 1, limit: 10, total: 0 });

const columns = ref([]);
const dataSource = ref([])

const change = (page: any) => {
  loading.value = true;
  setTimeout(() => {
    loadDataSource();
    loading.value = false;
  }, 500);
};

const firstQuery = async () => {
  loading.value = true;
  const queryCount = reactive({dblink_id: tableData.data.db_id, select: sql_data.value});
  let {result, status, message} = await selectCount(queryCount);
  if(status === 'success'){page.total = result.total;}else {layer.msg(message)}
  const querySql = reactive({dblink_id: tableData.data.db_id, select: sql_data.value,
                                    current: page.current, limit: page.limit});
  let response = await actSelectSql(querySql);
  if(response.status === 'success'){
    columns.value = response.result.columns;
    dataSource.value = response.result.data_source;
  }else {
    openMsg(status, message, 3000);
  }
  loading.value = false;
}

const loadDataSource = async () => {
  const querySql = reactive({dblink_id: tableData.data.db_id, select: sql_data.value,
                                    current: page.current, limit: page.limit});
  let {result, status, message} = await actSelectSql(querySql);
  if(status === 'success'){
    dataSource.value = result.data_source;
  }
};

</script>

<style scoped>

</style>